package com.weiter.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weiter.common.core.constant.CacheConstants;
import com.weiter.common.core.core.domain.entity.SysDictData;
import com.weiter.common.core.core.domain.entity.SysDictType;
import com.weiter.common.core.core.page.PageQuery;
import com.weiter.common.core.exception.ServiceException;
import com.weiter.common.core.utils.spring.SpringUtils;
import com.weiter.common.redis.service.RedisService;
import com.weiter.system.mapper.SysDictDataMapper;
import com.weiter.system.mapper.SysDictTypeMapper;
import com.weiter.system.service.ISysDictDataService;
import com.weiter.system.service.ISysDictTypeService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 字典类型
 * @author weiter
 */
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements ISysDictTypeService {

    @Resource
    private SysDictTypeMapper dictTypeMapper;

    @Resource
    private SysDictDataMapper dictDataMapper;

    @Resource
    private ISysDictDataService dictDataService;

    @Resource
    private RedisService redisService;

    /**
     * 项目启动时，初始化字典到缓存
     */
    @PostConstruct
    public void init() {
        loadingDictCache();
    }

    /**
     * 查询字典类型分页列表
     * @param query     字典类型查询条件
     * @param pageQuery 分页查询信息
     * @return 字典类型分页列表
     */
    @Override
    public Page<SysDictType> selectDictTypePage(SysDictType query, PageQuery pageQuery) {
        LambdaQueryWrapper<SysDictType> lqw = buildQueryWrapper(query);
        return dictTypeMapper.selectPage(pageQuery.build(), lqw);
    }

    /**
     * 查询字典类型列表
     * @param query 字典类型查询条件
     * @return 字典类型列表
     */
    @Override
    public List<SysDictType> selectDictTypeList(SysDictType query) {
        LambdaQueryWrapper<SysDictType> lqw = buildQueryWrapper(query);
        return dictTypeMapper.selectList(lqw);
    }

    /**
     * 新增字典类型信息
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    public int insertDictType(SysDictType dict) {
        int row = dictTypeMapper.insert(dict);
        if (row > 0) {
            dictDataService.setDictCache(dict.getDictType(), null);
        }
        return row;
    }

    /**
     * 修改字典类型信息
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDictType(SysDictType dict) {
        SysDictType oldDict = dictTypeMapper.selectById(dict.getDictId());
        dictDataMapper.update(null, new LambdaUpdateWrapper<SysDictData>()
                .set(SysDictData::getDictType, dict.getDictType())
                .eq(SysDictData::getDictType, oldDict.getDictType()));
        int row = dictTypeMapper.updateById(dict);
        if (row > 0) {
            List<SysDictData> dictDataList = dictDataService.selectDictDataByType(dict.getDictType());
            dictDataService.setDictCache(dict.getDictType(), dictDataList);
        }
        return row;
    }

    /**
     * 删除字典信息
     * @param dictIds 需要删除的字典ID
     */
    @Override
    public void deleteDictTypeByIds(Long[] dictIds) {
        for (Long dictId : dictIds) {
            SysDictType dictType = getById(dictId);
            Long used = dictDataMapper.selectCount(new LambdaQueryWrapper<SysDictData>().eq(SysDictData::getDictType, dictType.getDictType()));
            if (used > 0) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
            dictTypeMapper.deleteById(dictId);
            // 删除指定字典缓存
            redisService.deleteObject(CacheConstants.SYS_DICT_KEY + dictType.getDictType());
        }
    }

    /**
     * 校验字典类型称是否重复
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public boolean checkDictTypeDuplicate(SysDictType dict) {
        return baseMapper.exists(new LambdaQueryWrapper<SysDictType>()
                .eq(SysDictType::getDictType, dict.getDictType())
                .ne(ObjectUtil.isNotNull(dict.getDictId()), SysDictType::getDictId, dict.getDictId()));
    }

    /**
     * 加载字典缓存数据
     */
    @Override
    public void loadingDictCache() {
        List<SysDictData> dictDataList = dictDataMapper.selectList(new LambdaQueryWrapper<SysDictData>().eq(SysDictData::getStatus, 0));
        Map<String, List<SysDictData>> dictDataMap = dictDataList.stream().collect(Collectors.groupingBy(SysDictData::getDictType));
        for (Map.Entry<String, List<SysDictData>> entry : dictDataMap.entrySet()) {
            dictDataService.setDictCache(entry.getKey(), entry.getValue().stream().sorted(Comparator.comparing(SysDictData::getDictSort)).collect(Collectors.toList()));
        }
    }

    /**
     * 删除所有字典缓存数据
     */
    @Override
    public void clearDictCache() {
        Collection<String> keys = SpringUtils.getBean(RedisService.class).keys(CacheConstants.SYS_DICT_KEY + "*");
        redisService.deleteObject(keys);
    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache() {
        clearDictCache();
        loadingDictCache();
    }

    private LambdaQueryWrapper<SysDictType> buildQueryWrapper(SysDictType query) {
        Map<String, Object> params = query.getParams();
        LambdaQueryWrapper<SysDictType> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(query.getDictName()), SysDictType::getDictName, query.getDictName());
        lqw.eq(StrUtil.isNotBlank(query.getDictType()), SysDictType::getDictType, query.getDictType());
        lqw.eq(StrUtil.isNotBlank(query.getStatus()), SysDictType::getStatus, query.getStatus());
        lqw.between(params.get("beginTime") != null && params.get("endTime") != null,
                SysDictType::getCreateTime, params.get("beginTime"), params.get("endTime"));
        lqw.orderByAsc(SysDictType::getCreateTime);
        return lqw;
    }
}
